﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.Windows.Forms;
using DevLib.ExtensionMethods;
using DevLib.ModernUI.Forms;
using Microsoft.Win32;

namespace wsy.tools.java.configpath
{
    public partial class Form1 : ModernForm
    {
        public string JavaPath { get; set; }
        public string JavaPlaform { get; set; }

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            bool isRunasAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
            if (!isRunasAdmin)
            {
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName = Application.ExecutablePath;
                psi.Verb = "runas";
                Process.Start(psi);
                Application.Exit();
            }
            else
            {
                GetJava();
            }
            
        }

        private bool GetJavaPath(RegistryView view)
        {
            JavaPath = null;
            RegistryKey HLM = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, view);
            RegistryKey SOFT = HLM.OpenSubKey("SOFTWARE");
            RegistryKey JavaSoft = SOFT.OpenSubKey("JavaSoft");
            if (JavaSoft == null)
            {
                JavaPath = null;
                return false;
            }
            RegistryKey JDK = JavaSoft.OpenSubKey("Java Development Kit");
            if (JDK == null)
            {
                JavaPath = null;
                return false;
            }
            var jdkversions = JDK.GetSubKeyNames();
            if (jdkversions.Length == 0)
            {
                JavaPath = null;
                return false;
            }
            foreach (string t in jdkversions)
            {
                JavaPath = JDK.OpenSubKey(t)?.GetValue("JavaHome")?.ToString();
                if (JavaPath != null) break;
            }
            if (JavaPath != null)
            {
                JavaPlaform = view == RegistryView.Registry64 ? "x64" : "x32";
                modernLabel1.Text = JavaPath;
                modernLabel2.Text = JavaPlaform;
                return true;
            }
            return false;
//
//
//            string javacmd = "java -verbose".RunCmd();
//            Match match = Regex.Match(javacmd, "Opened (?<grp0>.+?)\\\\lib\\\\rt\\.jar");
//            if (match.Success)
//            {
//                JavaPath = match.Groups["grp0"].Value;
//                return true;
//            }
//            JavaPath = null;
//            return false;
        }

        private bool GetJava()
        {
            return GetJavaPath(RegistryView.Registry64) || GetJavaPath(RegistryView.Registry32);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (JavaPath.IsNullOrWhiteSpace()||JavaPlaform.IsNullOrWhiteSpace())
            {
                ModernMessageBox.Show("Java 没有安装好！");
                return;
            }
            try
            {
                button1.Enabled = false;
                string classpath=  Environment.GetEnvironmentVariable("CLASSPATH")??"";
                var paths = (Environment.GetEnvironmentVariable("PATH") ?? "").Split(';');
                HashSet<string> pathls = new HashSet<string>(paths) {"%JAVA_HOME%\\bin"};
                string strpath = pathls.Aggregate("", (current, s) => current + (s + ";"));
                Environment.SetEnvironmentVariable("JAVA_HOME", JavaPath,EnvironmentVariableTarget.Machine);
                Environment.SetEnvironmentVariable("CLASSPATH",classpath + ".;%JAVA_HOME%\\lib\\dt.jar;%JAVA_HOME%\\lib\\tools.jar;",EnvironmentVariableTarget.Machine);
                Environment.SetEnvironmentVariable("PATH", strpath, EnvironmentVariableTarget.Machine);
                ModernMessageBox.Show("配置成功", "信息");
                Application.Exit();
                
            }
            catch (Exception ex)
            {
                ModernMessageBox.Show(ex.Message, "error");
            }
        }
    }
}
